package org.jeecg.modules.pipe.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.TenantConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SysTenantVo;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.device.service.IDevDeviceRecordService;
import org.jeecg.modules.pipe.entity.MonitorPoint;
import org.jeecg.modules.pipe.service.IMonitorPointService;
import org.jeecg.modules.pipe.vo.PipeMarkerVo;
import org.jeecg.modules.pipe.vo.PipeQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 监测点
 * @Author: jeecg-boot
 * @Date:   2024-05-18
 * @Version: V1.0
 */
@Api(tags="监测点")
@RestController
@RequestMapping("/pipe/monitorPoint")
@Slf4j
public class MonitorPointController extends JeecgController<MonitorPoint, IMonitorPointService> {
	@Autowired
	private IMonitorPointService monitorPointService;
	@Autowired
	private IDevDeviceRecordService deviceRecordService;
	@Autowired
	private RedisUtil redisUtil;
	
	/**
	 * 分页列表查询
	 *
	 * @param monitorPoint
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "监测点-分页列表查询")
	@ApiOperation(value="监测点-分页列表查询", notes="监测点-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<MonitorPoint>> queryPageList(MonitorPoint monitorPoint,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MonitorPoint> queryWrapper = QueryGenerator.initQueryWrapper(monitorPoint, req.getParameterMap());
		Page<MonitorPoint> page = new Page<MonitorPoint>(pageNo, pageSize);
		IPage<MonitorPoint> pageList = monitorPointService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param monitorPoint
	 * @return
	 */
	@AutoLog(value = "监测点-添加")
	@ApiOperation(value="监测点-添加", notes="监测点-添加")
	// @RequiresPermissions("pipe:iot_pipe_monitor_point:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MonitorPoint monitorPoint) {
		if(StringUtils.isEmpty(monitorPoint.getCode())){
			MonitorPoint one = monitorPointService.getOne(Wrappers.<MonitorPoint>lambdaQuery()
					.eq(MonitorPoint::getDelFlag, 0)
					.orderByAsc(MonitorPoint::getCode).last("limit 1"));
			if(null != one){
				String code = one.getCode();
				long codeLong=Long.parseLong(code)+1;
				monitorPoint.setCode(codeLong+"");
			}else {
				//租户地区编号+四位顺序编号
				Object tenantObj = redisUtil.hget(TenantConstant.SYS_TENANT_CACHE_MAP, null!= TenantContext.getTenant()?TenantContext.getTenant():"0");
				if(null != tenantObj ){
					SysTenantVo tenantVo = (SysTenantVo)tenantObj;
					String address = tenantVo.getAddress();//区划编码
					if(StringUtils.isNotEmpty(address)){
						monitorPoint.setCode(address+"1001");
					}else{
						monitorPoint.setCode("00001001");
					}
				}else{
					monitorPoint.setCode("00001001");
				}
			}
		}
		monitorPointService.save(monitorPoint);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param monitorPoint
	 * @return
	 */
	@AutoLog(value = "监测点-编辑")
	@ApiOperation(value="监测点-编辑", notes="监测点-编辑")
	// @RequiresPermissions("pipe:iot_pipe_monitor_point:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody MonitorPoint monitorPoint) {
		if(StringUtils.isEmpty(monitorPoint.getCode())){
			MonitorPoint one = monitorPointService.getOne(Wrappers.<MonitorPoint>lambdaQuery()
					.eq(MonitorPoint::getDelFlag, 0)
					.ne(MonitorPoint::getId,monitorPoint.getId())
					.orderByAsc(MonitorPoint::getCode).last("limit 1"));
			if(null != one){
				String code = one.getCode();
				if(StringUtils.isEmpty(code)){
					monitorPoint.setCode("00001001");
				}else{
					long codeLong=Long.parseLong(code)+1;
					monitorPoint.setCode(codeLong+"");
				}
			}else {
				//租户地区编号+四位顺序编号
				Object tenantObj = redisUtil.hget(TenantConstant.SYS_TENANT_CACHE_MAP, null!= TenantContext.getTenant()?TenantContext.getTenant():"0");
				if(null != tenantObj ){
					SysTenantVo tenantVo = (SysTenantVo)tenantObj;
					String address = tenantVo.getAddress();//区划编码
					if(StringUtils.isNotEmpty(address)){
						monitorPoint.setCode(address+"1001");
					}else{
						monitorPoint.setCode("00001001");
					}
				}else{
					monitorPoint.setCode("00001001");
				}
			}
		}
		monitorPointService.updateById(monitorPoint);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "监测点-通过id删除")
	@ApiOperation(value="监测点-通过id删除", notes="监测点-通过id删除")
	// @RequiresPermissions("pipe:iot_pipe_monitor_point:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		monitorPointService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "监测点-批量删除")
	@ApiOperation(value="监测点-批量删除", notes="监测点-批量删除")
	// @RequiresPermissions("pipe:iot_pipe_monitor_point:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.monitorPointService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "监测点-通过id查询")
	@ApiOperation(value="监测点-通过id查询", notes="监测点-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<MonitorPoint> queryById(@RequestParam(name="id",required=true) String id) {
		MonitorPoint monitorPoint = monitorPointService.getById(id);
		if(monitorPoint==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(monitorPoint);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param monitorPoint
    */
    // @RequiresPermissions("pipe:iot_pipe_monitor_point:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MonitorPoint monitorPoint) {
        return super.exportXls(request, monitorPoint, MonitorPoint.class, "监测点");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    // @RequiresPermissions("pipe:iot_pipe_monitor_point:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MonitorPoint.class);
    }

	/**
	 * 获取监测点列表查询
	 *
	 * @param queryVo
	 * @return
	 */
	//@AutoLog(value = "水厂信息表-分页列表查询")
	@ApiOperation(value="监测点列表查询", notes="监测点列表查询")
	@GetMapping(value = "/api/getList")
	public Result<List<PipeMarkerVo>> getList(PipeQueryVo queryVo) {
		List<PipeMarkerVo> list = monitorPointService.getMonitorPointMarker(queryVo);
		return Result.OK(list);
	}

	/**
	 * 根据监测点获取设备列表-数据
	 * @param pointId
	 * @return
	 */
	//@AutoLog(value = "水库信息表-分页列表查询")
	@ApiOperation(value="根据监测点获取设备列表-数据", notes="根据监测点获取设备列表-数据")
	@GetMapping(value = "/api/getDeviceListData/{pointId}")
	public Result<List<Map<String, Object>>> getDeviceList(@PathVariable("pointId") String pointId) {
		return Result.OK(monitorPointService.getDeviceListReadTimeData(pointId));
	}
}
